﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraGrid.Columns;
using DevTeam;
using System;
using System.Collections.Generic;
using System.Data;

namespace ConfExpert.Forms.Siparisler
{
    public partial class PackingList : XForm
    {
        public PackingList()
        {
            InitializeComponent();
        }

        int YuklemePartisiId = 0;
        public PackingList(int YuklemePartisiId)
            : this()
        {
            this.YuklemePartisiId = YuklemePartisiId;
            this.Text += " - YP." + YuklemePartisiId.ToStr();
        }

        Dictionary<string, string> dx = new Dictionary<string, string>();
        private void PackingList_Load(object sender, EventArgs e)
        {
            gridView1.Init("GetPackingList", YuklemePartisiId, string.Empty, 0);
            gridView1.AddDetailGrid(gridView2, "PackingListId");

            gridView3.Init("GetPackingList_Empty");

            DataTable dxTable = ExecuteDataTable("GetPLDx", YuklemePartisiId);
            foreach (DataRow r in dxTable.Rows)
                dx.Add(r["Caption"].ToStr(), r["COLUMN_NAME"].ToStr());

            foreach (string col in "Model,Renk,Magaza,Ulke,Ek1,Ek2,Ek3,Ek4,Ek5,Ek6,Ek7,Ek8,Ek9".Split(",".ToCharArray()))
                if (gridView2.DataTable().Select(col + " is not null").Length == 0)
                    gridView2.Columns[col].Visible = false;

            gridView1.DataTable().SetPK("PackingListId");
            gridView2.DataTable().SetPK("PackingListLinesId");
            gridView3.AddAutoIncrementalPK("PackingListLinesId");

            gridView1.MakeColumnInvisible("PlanlamaId", "InsertedOn", "DagilimId", "YuklemePartisiId", "Basla", "Bitir", "PLTemplateId");
            gridView2.MakeColumnInvisible("PackingListLinesId", "UserId", "PlanlamaId", "idx");
            gridView1.AddColumn("Toplam", typeof(int), "SUM(Child({FK}).Toplam)");
            gridView1.FormatAsNumber(0, "Toplam");
            gridView1.AddSummary("Toplam");

            gridView1.BestFitColumns();

            //DagilimChanged();
            //gridView2.ShowOnlyNonblankColumns();
            gridView2.BestFitColumns();

            btnKaydet.ItemClick += btnKaydet_ItemClick;
            gridView1.MakeReadOnly();
            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
            gridView1.MakeRowSelectable();

            GridMenu gm = GridManager.GetManager(gridView2).GridMenu;
            gm.AddMenu("Satır ekle", SatirEkle);

            gridView1_FocusedRowChanged(null, null);
            ExpandCollapse(splitContainerControl1, AcKapa.Collapse);
        }

        private void SatirEkle(object sender, EventArgs e)
        {
            DataRow copied = gridView2.GetFocusedDataRow();
            gridView3.AddNewRow();

            int rowHandle = gridView3.GetRowHandle(gridView3.DataRowCount);
            if (gridView3.IsNewItemRow(rowHandle))
            {
                gridView3.SetRowCellValue(rowHandle, "PackingListId", copied["PackingListId"]);
                gridView3.SetRowCellValue(rowHandle, "Renk", copied["Renk"]);
                gridView3.SetRowCellValue(rowHandle, "Magaza", copied["Magaza"]);
                //gridView3.SetRowCellValue(rowHandle, "Sehir", copied["Sehir"]);   //TODO!
                gridView3.SetRowCellValue(rowHandle, "Ulke", copied["Ulke"]);
            }

            gridView3.MoveLast();
        }

        bool rfrsh = false;
        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (!rfrsh)
            {
                DagilimChanged();
                //gridView2.ShowOnlyNonblankColumns();
                gridView2.BestFitColumns();

                Sync();
            }
        }

        private void Sync()
        {
            foreach (GridColumn col in gridView2.Columns)
                if (gridView3.Columns[col.FieldName] != null)
                {
                    gridView3.Columns[col.FieldName].VisibleIndex = col.VisibleIndex;
                    if (col.VisibleIndex > -1)
                        gridView3.Columns[col.FieldName].Width = col.Width;
                }
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                rfrsh = true;

                gridView1.EndEditing();
                gridView2.EndEditing();
                gridView3.EndEditing();

                int PackingListId = gridView1.GetFocusedDataRow()["PackingListId"].ToInt();
                int PackingListLinesId = gridView2.GetFocusedDataRow()["PackingListLinesId"].ToInt();

                gridView2.Update("", "PackingListLines");

                string xml = gridView3.Serialize();
                gridView1.RefreshDataSource("GetPackingList", YuklemePartisiId, xml, WhoAmI);
                gridView3.RefreshDataSource("GetPackingList_Empty");

                gridView1.BestFitColumns();
                gridView1.FocusedRowHandle = gridView1.LocateByValue("PackingListId", PackingListId);
                gridView1.MakeRowVisible(gridView1.FocusedRowHandle);

                gridView2.BestFitColumns();
                gridView2.FocusedRowHandle = gridView2.LocateByValue("PackingListLinesId", PackingListLinesId);
                gridView2.MakeRowVisible(gridView2.FocusedRowHandle);

                Sync();
            }
            finally
            {
                rfrsh = false;
            }
        }

        int DagilimId = 0;

        private void DagilimChanged()
        {
            try
            {
                gridView2.CloseEditor();
                gridView2.BeginUpdate();
                gridView3.BeginUpdate();

                gridView2.DataTable().Columns["Toplam"].Expression = "ISNULL(A01,0)+ISNULL(A02,0)+ISNULL(A03,0)+ISNULL(A04,0)+ISNULL(A05,0)+ISNULL(A06,0)+ISNULL(A07,0)+ISNULL(A08,0)+ISNULL(A09,0)+ISNULL(A10,0)+ISNULL(A11,0)+ISNULL(A12,0)+ISNULL(A13,0)+ISNULL(A14,0)+ISNULL(A15,0)+ISNULL(A16,0)+ISNULL(A17,0)+ISNULL(A18,0)+ISNULL(A19,0)+ISNULL(A20,0)+ISNULL(A21,0)+ISNULL(A22,0)+ISNULL(A23,0)+ISNULL(A24,0)+ISNULL(A25,0)+ISNULL(A26,0)+ISNULL(A27,0)+ISNULL(A28,0)";
                gridView2.FormatAsNumber(0, "Toplam");
                gridView2.AddSummary("Toplam");

                gridView3.DataTable().Columns["Toplam"].Expression = "ISNULL(A01,0)+ISNULL(A02,0)+ISNULL(A03,0)+ISNULL(A04,0)+ISNULL(A05,0)+ISNULL(A06,0)+ISNULL(A07,0)+ISNULL(A08,0)+ISNULL(A09,0)+ISNULL(A10,0)+ISNULL(A11,0)+ISNULL(A12,0)+ISNULL(A13,0)+ISNULL(A14,0)+ISNULL(A15,0)+ISNULL(A16,0)+ISNULL(A17,0)+ISNULL(A18,0)+ISNULL(A19,0)+ISNULL(A20,0)+ISNULL(A21,0)+ISNULL(A22,0)+ISNULL(A23,0)+ISNULL(A24,0)+ISNULL(A25,0)+ISNULL(A26,0)+ISNULL(A27,0)+ISNULL(A28,0)";
                gridView3.FormatAsNumber(0, "Toplam");
                gridView3.AddSummary("Toplam");

                gridView2.YanYanaGetirSoluna("Toplam", "A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10", "A11", "A12", "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20", "A21", "A22", "A23", "A24", "A25", "A26", "A27", "A28");
                gridView3.YanYanaGetirSoluna("Toplam", "A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10", "A11", "A12", "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20", "A21", "A22", "A23", "A24", "A25", "A26", "A27", "A28");

                DagilimId = gridView1.GetFocusedRowCellValue("DagilimId").ToInt();
                int Basla = gridView1.GetFocusedRowCellValue("Basla").ToInt();
                int Bitir = gridView1.GetFocusedRowCellValue("Bitir").ToInt();

                MyData.DagilimRow r = AppSession.Lookups.Dagilim.FindByDagilimId(DagilimId);
                if (r != null)
                    for (int i = 1; i < 29; i++)
                    {
                        string fieldName = String.Format("A{0:00}", i);
                        string cap = r[String.Format("A{0:00}", i)].ToString();
                        gridView2.Columns[fieldName].Caption = cap != string.Empty ? cap : " ";
                        gridView3.Columns[fieldName].Caption = cap != string.Empty ? cap : " ";

                        if (!(i >= Basla && i <= Bitir))
                            gridView2.Columns[fieldName].Visible =
                            gridView3.Columns[fieldName].Visible =
                            false;
                    }

                foreach (KeyValuePair<string, string> p in dx)
                    gridView2.Columns[p.Value].Caption = gridView3.Columns[p.Value].Caption = p.Key;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                gridView2.EndUpdate();
                gridView3.EndUpdate();
            }
        }
    }
}
